from django.db import transaction
from rest_framework import serializers
from .models import *
from django.db.utils import IntegrityError

class ProductPicSerializer(serializers.ModelSerializer):
    class Meta:
        model=ProductPic
        exclude='product',

class ProductStyleSerializer(serializers.ModelSerializer):
    class Meta:
        model=ProductStyle
        exclude='product',

class ProductSerializer(serializers.ModelSerializer):
    gender=serializers.SerializerMethodField()
    type = serializers.SerializerMethodField()
    category = serializers.SerializerMethodField()
    pic = ProductPicSerializer(many=True,label='图片列表')
    style=ProductStyleSerializer(many=True,label='款式列表')
    size=serializers.SerializerMethodField()
    class Meta:
        model=Product
        fields='__all__'
    def get_gender(self,obj):
        return obj.get_gender_display()
    def get_type(self,obj):
        return obj.get_type_display()
    def get_category(self,obj):
        return obj.category.title
    def get_size(self,obj):
        size=[]
        if obj.size:
            size=obj.size.split('|')
        return size


class ShopCartSerializer(serializers.ModelSerializer):
    class Meta:
        model=ShopCart
        exclude='user',


    def save(self, **kwargs):
        request = self.context['request']
        self.validated_data['user'] =request.user
        try:
            obj=super().save(**kwargs)
        except IntegrityError:
            obj=ShopCart.objects.get(
                user=self.validated_data['user'],
                product=self.validated_data['product'],
                style = self.validated_data['style'],
                size = self.validated_data['size'],
            )
            obj.count +=self.validated_data['count']
            obj.save()
        return obj

class ShopOrderSerializer(serializers.ModelSerializer):
    item_list = serializers.PrimaryKeyRelatedField(
        label="购物车条目的id列表", many=True, allow_empty=False,
        queryset=ShopCart.objects.all()
    )

    class Meta:
        model = ShopOrder
        exclude = ("user",)

    @transaction.atomic() # 事务打包
    def save(self, **kwargs):
        request = self.context['request']
        self.validated_data['user'] = request.user
        item_list = self.validated_data.pop("item_list")

        obj = super().save(**kwargs)

        _item_list = []
        for item in item_list:
            _item_list.append(ShopItem.objects.create(
                order=obj,
                style=item.style,
                size=item.size,
                count=item.count,
                price=item.product.sales_price,
            ))
        # 删除购物车买过的商品
        # for item in item_list:
        #     item.delete()
        ShopCart.objects.filter(id__in=[_.id for _ in item_list]).delete()

        return obj


class ShopOrderOutSerializer(ShopOrderSerializer):
    item_list = None


